﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

using Common.Model;
using Common.Error;
using OpenAPI.IDAL;
using OpenAPI.Model.OAuth;
using OpenAPI.BLL.OAuth;

namespace OpenAPI.ProxyBLL
{
    public class APIProxyManager : IAPIProxy
    {

        /// <summary>
        /// 执行API方法
        /// </summary>
        /// <param name="method"></param>
        /// <param name="unSignArgumets"></param>
        /// <param name="signArgumets"></param>
        /// <returns>XML</returns>
        public string ExecuteAPIMethod(string method, ArrayList unSignArgumets, ArrayList signArgumets)
        {
            StringBuilder xml = new StringBuilder();
            switch (method.ToLower().Trim())
            {
                #region OAuth类API
                case "openapi.oauth.requesttoken":
                    xml = this.OpenAPI_OAuth_RequestToken(method, unSignArgumets, signArgumets);
                    break;
                case "openapi.oauth.authorizetoken":
                    xml = this.OpenAPI_OAuth_AuthorizeToken(method, unSignArgumets, signArgumets);
                    break;
                case "openapi.oauth.exchangeaccesstoken":
                    xml = this.OpenAPI_OAuth_ExchangeAccessToken(method, unSignArgumets, signArgumets);
                    break;
                #endregion
            }

            return xml.ToString();
        }

        /// <summary>
        /// 获取参数值
        /// </summary>
        /// <param name="arguments">参数数组</param>
        /// <param name="name">参数名称</param>
        /// <returns></returns>
        private string GetArgumentValue(ArrayList arguments, string name)
        {
            string value = "";

            foreach (ArgumentInfo argument in arguments)
            {
                if (argument.Name.ToLower() == name.ToLower())
                {
                    value = argument.Value;
                    break;
                }
            }

            return value;
        }

        #region API

        #region OAuth类API

        /// <summary>
        /// 向服务提供方请求令牌及令牌密钥
        /// </summary>
        /// <returns></returns>
        private StringBuilder OpenAPI_OAuth_RequestToken(string method, ArrayList unSignArgumets, ArrayList signArgumets)
        {
            StringBuilder xml = new StringBuilder();
            ResultInfo result = new ResultInfo();
            bool result_stat = false;
            ErrorType error = null;

            string oauth_consumer_key = this.GetArgumentValue(unSignArgumets, "oauth_consumer_key");
            long oauth_timestamp = long.Parse(this.GetArgumentValue(signArgumets, "oauth_timestamp"));
            string oauth_nonce = this.GetArgumentValue(signArgumets, "oauth_nonce");

            AuthorizeTokenInfo new_token = new AuthorizeTokenInfo();
            new_token.OAUTH_CONSUMER_KEY = oauth_consumer_key;
            new_token.OAUTH_TOKEN = Utility.StringHelper.GetMd5String(Utility.StringHelper.GetGuidString());
            new_token.OAUTH_TOKEN_SECRET = Utility.StringHelper.GetMd5String(Utility.StringHelper.GetGuidString());
            new_token.OAUTH_TOKEN_STATUS = 0;  //请求时，把状态设为不可用
            new_token.OAUTH_TOKEN_REQUEST_TIMESTAMP = oauth_timestamp;
            new_token.OAUTH_TOKEN_AUTHORIZE_TIMESTAMP = 0;
            new_token.OAUTH_NONCE = oauth_nonce;

            AuthorizeTokenInfo req_token = OpenAPI.BLL.OAuth.ConsumerManager.RequestToken(oauth_consumer_key, new_token, out error);
            if (req_token != null)
            {
                ArrayList data = new ArrayList();
                data.Add(req_token);

                result.FLAG = true;
                result.CODE = "";
                result.DESC = "ok";
                result.DATA = data;
            }
            else
            {
                result.FLAG = false;
                result.CODE = error.ERROR_CODE;
                result.DESC = error.ERROR_MESSAGE;
                result.DATA = null;
            }

            xml.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?> ");
            xml.AppendLine("<rsp method=\"" + method + "\" flag=\"" + result.FLAG.ToString() + "\" code=\"" + result.CODE + "\"  desc=\"" + result.DESC + "\" >");
            xml.AppendLine("<data>");
            if (result.DATA != null)
            {
                xml.AppendLine("<token>" + ((AuthorizeTokenInfo)result.DATA[0]).OAUTH_TOKEN + "</token>");
                xml.AppendLine("<token_secret>" + ((AuthorizeTokenInfo)result.DATA[0]).OAUTH_TOKEN_SECRET + "</token_secret>");
            }
            xml.AppendLine("</data>");
            xml.AppendLine("</rsp>");

            return xml;
        }

        /// <summary>
        /// 验证令牌及密钥
        /// </summary>
        /// <returns></returns>
        private StringBuilder OpenAPI_OAuth_AuthorizeToken(string method, ArrayList unSignArgumets, ArrayList signArgumets)
        {
            StringBuilder xml = new StringBuilder();
            ResultInfo result = new ResultInfo();
            bool result_stat = false;
            ErrorType error = null;

            string oauth_consumer_key = this.GetArgumentValue(unSignArgumets, "oauth_consumer_key");
            string oauth_token = this.GetArgumentValue(unSignArgumets, "oauth_token");
            long oauth_timestamp = long.Parse(this.GetArgumentValue(signArgumets, "oauth_timestamp"));
            string oauth_nonce = this.GetArgumentValue(signArgumets, "oauth_nonce");

            AuthorizeTokenInfo authToken = new AuthorizeTokenInfo();
            authToken.OAUTH_CONSUMER_KEY = oauth_consumer_key;
            authToken.OAUTH_TOKEN = oauth_token;
            authToken.OAUTH_TOKEN_SECRET = OpenAPI.BLL.OAuth.ConsumerManager.GetOAuthTokenSecret(oauth_consumer_key, oauth_token, out error);
            authToken.OAUTH_TOKEN_AUTHORIZE_TIMESTAMP = oauth_timestamp;
            authToken.OAUTH_NONCE = oauth_nonce;

            AuthorizeTokenInfo auth_token = OpenAPI.BLL.OAuth.ConsumerManager.AuthorizeToken(authToken, out error);
            if (auth_token != null)
            {
                ArrayList data = new ArrayList();
                data.Add(auth_token);

                result.FLAG = true;
                result.CODE = "";
                result.DESC = "ok";
                result.DATA = data;
            }
            else
            {
                result.FLAG = false;
                result.CODE = error.ERROR_CODE;
                result.DESC = error.ERROR_MESSAGE;
                result.DATA = null;
            }

            xml.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?> ");
            xml.AppendLine("<rsp method=\"" + method + "\" flag=\"" + result.FLAG.ToString() + "\" code=\"" + result.CODE + "\"  desc=\"" + result.DESC + "\" >");
            xml.AppendLine("<data>");
            if (result.DATA != null)
            {
                xml.AppendLine("<token>" + ((AuthorizeTokenInfo)result.DATA[0]).OAUTH_TOKEN + "</token>");
                xml.AppendLine("<token_secret>" + ((AuthorizeTokenInfo)result.DATA[0]).OAUTH_TOKEN_SECRET + "</token_secret>");
            }
            xml.AppendLine("</data>");
            xml.AppendLine("</rsp>");
            return xml;
        }

        /// <summary>
        /// 换取访问令牌及密钥
        /// </summary>
        /// <returns></returns>
        private StringBuilder OpenAPI_OAuth_ExchangeAccessToken(string method, ArrayList unSignArgumets, ArrayList signArgumets)
        {
            StringBuilder xml = new StringBuilder();

            return xml;
        }

        #endregion

        #endregion
    }
}
